# encoding: utf-8


import sys

from configs import *


# imprime a tabulação para indentar o código corretamente
def printIndentation( indentLevel ):
    global TABSIZE
    print( TABSIZE * indentLevel * ' ' ),
#----------------------------------------


# lê o nome do arquivo com o modelo Ecore de entrada
def getInputFileName():
    if len( sys.argv ) != 2:
        print( 'Erro. Uso: {0} <modelo.ecore>'.format( sys.argv[0] ) )
        sys.exit( 1 )
    
    return sys.argv[1]
#-----------------------------------

    
# Lê o conteúdo do arquivo modelo Ecore
def getFileContents( filename ):
    fp = open( filename )
    contents = fp.read()
    fp.close()
    
    return contents
#----------------------------------------


# função principal, que chama os métodos específicos de parsing
def parseEcoreToJSON( domObject, indentLevel ):
    if getTotalPackages( domObject ) > 0:
       indentLevel = parseEcorePackage( domObject, indentLevel )
    else:
        if getTotalClassifiers( domObject ) > 0:
            indentLevel = parseEcoreClassifiers( domObject, indentLevel )
#-----------------------------------------


def getTotalPackages( domObject ):
    eSubpackages = domObject.getElementsByTagName( 'eSubpackages' )
    totalPackages = len( eSubpackages )
    
    return totalPackages
#-----------------------------------

# faz o parse de um pacote Ecore
def parseEcorePackage( domObject, indentLevel ):
    eSubpackages = domObject.getElementsByTagName( 'eSubpackages' )
    totalPackages = len( eSubpackages )
    packageCounter = 0
    for package in eSubpackages:
        packageCounter = packageCounter + 1;
        indentLevel = indentLevel + 1
        packageName = package.getAttributeNode( 'name' ).nodeValue

        # abre o pacote
        printIndentation( indentLevel )
        print( '"' + str( packageName ) + '" : {' )

        if getTotalClassifiers( domObject ) > 0:
            indentLevel = parseEcoreClassifiers( domObject, indentLevel )


        # fecha o pacote
        printIndentation( indentLevel )
        print( '}' ),
        if packageCounter < packageCounter:
            print( ',' ),
        print
        indentLevel = indentLevel - 1
    
    return indentLevel
#-----------------------------------------


# retorna o total de objetos Classifiers (classe e enumeradores)
def getTotalClassifiers( domObject ):
    eClassifiers = domObject.getElementsByTagName( 'eClassifiers' )
    totalClassifiers = len( eClassifiers )
    
    return totalClassifiers
#--------------------------------------------


# faz o parse de um classifier Ecore (classe ou enumerador)
def parseEcoreClassifiers( domObject, indentLevel ):
    eClassifiers = domObject.getElementsByTagName( 'eClassifiers' )
    totalClassifiers = len( eClassifiers )
    classifierCounter = 0
    for classifier in eClassifiers:
        classifierCounter = classifierCounter + 1;
        indentLevel = indentLevel + 1
        attrType = classifier.getAttributeNode( 'xsi:type' )

        if attrType.nodeValue == 'ecore:EClass':
            classname = classifier.getAttributeNode( 'name' ).nodeValue

            # abre a classe
            printIndentation( indentLevel )
            print( '"' + classname + '" : {' )

            eStructuralFeatures = classifier.getElementsByTagName( 'eStructuralFeatures' )

            totalFeatures = len( eStructuralFeatures )
            featuresCounter = 0
            for feature in eStructuralFeatures:
                featuresCounter = featuresCounter + 1
                indentLevel = indentLevel + 1
                featureType = feature.getAttributeNode( 'xsi:type' )

                if featureType.nodeValue == 'ecore:EAttribute':
                    featureName = feature.getAttributeNode( 'name' ).nodeValue

                    # adiciona um atributo
                    printIndentation( indentLevel )
                    print( '"' + featureName + '" : ""' ),
                    if featuresCounter < totalFeatures:
                        print( ',' ),
                    print


                indentLevel = indentLevel - 1

            # fecha a classe
            printIndentation( indentLevel )
            print( '}' ),
            if classifierCounter < totalClassifiers:
                print( ',' ),
            print

            indentLevel = indentLevel - 1
            
            
        # parse de EEnum
        if attrType.nodeValue == 'ecore:EEnum':
            enumName = classifier.getAttributeNode( 'name' ).nodeValue

            # abre o enum
            printIndentation( indentLevel )
            print( '"' + str( enumName ) + '" : {' )

            eLiterals = classifier.getElementsByTagName( 'eLiterals' )

            totalLiterals = len( eLiterals )
            literalsCounter = 0
            for literal in eLiterals:
                literalsCounter = literalsCounter + 1
                indentLevel = indentLevel + 1
                literalName = literal.getAttributeNode( 'name' ).nodeValue
                literalValue = literal.getAttributeNode( 'value' )
                
                if literalValue == None:
                    literalValue = 0
                else:
                    literalValue = literalValue.nodeValue
                
                # adiciona um valor de anumerador
                printIndentation( indentLevel )
                print( '"' + str( literalName ) + '" : ' + str( literalValue ) ),
                if literalsCounter < totalLiterals:
                    print( ',' ),
                print


                indentLevel = indentLevel - 1

            # fecha a classe
            printIndentation( indentLevel )
            print( '}' ),
            if classifierCounter < totalClassifiers:
                print( ',' ),
            print

            indentLevel = indentLevel - 1
    
    return indentLevel
#--------------------------------------------












